package org.liaohailong.library.util

import android.content.Context
import java.io.BufferedReader
import java.io.Closeable
import java.io.InputStreamReader

/**
 * Author: liaohailong
 * Date: 2019/3/22
 * Time: 17:52
 * Description:
 **/
object AppInstallUtil {

    /**
     * 静默安装
     * 需要本app为系统级别的app
     * @param apkPath apk安装路径
     * @return 是否安装成功
     */
    fun install(apkPath: String, callback: OnAppInstallCallback) {
        val process = ProcessBuilder("pm", "install", "-r", apkPath).start()//7.0以下
//        val process = ProcessBuilder("pm", "install", "-i", "org.liaohailong.victorlibrary", "--user", "0", apkPath).start()//7.0
        process(process, callback)
    }

    /**
     * 卸载app
     * @param packageName 卸载程序的包名
     * @return 是否卸载成功
     */
    fun uninstall(packageName: String, callback: OnAppInstallCallback) {
        val process = ProcessBuilder("pm", "uninstall", packageName).start()
        process(process, callback)
    }

    fun exist(context: Context, packageName: String): Boolean {
        try {
            val installedPackages = context.packageManager.getInstalledPackages(0)
            for (packageInfo in installedPackages) {
                if (packageInfo.packageName.equals(packageName, true)) {
                    return true
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    fun process(process: Process, callback: OnAppInstallCallback) {
        var successResult: BufferedReader? = null
        var errorResult: BufferedReader? = null
        val successMsg = StringBuilder()
        val errorMsg = StringBuilder()

        try {
            successResult = BufferedReader(InputStreamReader(process.inputStream))
            errorResult = BufferedReader(InputStreamReader(process.errorStream))
            var s: String?
            while (true) {
                s = successResult.readLine()
                if (s != null) {
                    successMsg.append(s)
                } else break
            }
            while (true) {
                s = errorResult.readLine()
                if (s != null) {
                    errorMsg.append(s)
                } else break
            }

        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            closeIO(successResult)
            closeIO(errorResult)
            process.destroy()
        }
        val success = successMsg.toString().equals("success", true)
        if (success)
            callback.onAppInstallFinish(null)
        else
            callback.onAppInstallFinish(errorMsg.toString())
    }

    private fun closeIO(closeable: Closeable?) {
        try {
            closeable?.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    interface OnAppInstallCallback {
        fun onAppInstallFinish(errorMsg: String?)
    }
}